//
//  AppDelegate.swift
//  波波微博
//
//  Created by wave on 15/7/27.
//  Copyright © 2015年 wave. All rights reserved.
//////////////

import UIKit

//1. 定义一个通知名字,这样以后调用方便
let BBBSwitchMainInterfaceNotification = "BBBSwitchMainInterfaceNotification"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    
    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        print(UserAccount.sharedUserAccount)
        
        //2. 注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchRootViewController:", name: BBBSwitchMainInterfaceNotification, object: nil)
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        
        window?.backgroundColor = UIColor.whiteColor()

        window?.rootViewController = defaultViewController()
        
        window?.makeKeyAndVisible()
        
        setupAppearance()
        
        return true
    }

    //3. 根据通知切换视图控制器
    func switchRootViewController(n:NSNotification){
        
        let isMain = n.object as! Bool
        
        window?.rootViewController = isMain ? MainViewController() : WelcomeViewController()
    }

    private func defaultViewController()->UIViewController{
    
        //判断用户是否登陆,如果没有登陆返回Main控制器
        if !UserAccount.userLogn{
            return MainViewController()
        }
        
        return isNewUpdate() ? NewFeatureViewController() : WelcomeViewController()
    }
    
    //检查是否有新版本
    private func isNewUpdate()->Bool{
    
        //1. 获取程序当前版本
        let currentVersion = Double(NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String)!
        
        //2. 获取程序"之前"的版本,偏好设置
        let sandboxVersionKey = "sandboxVersionKey"
        let sandboxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(sandboxVersionKey)
        
        //3. 将当前版本保存至沙盒
        NSUserDefaults.standardUserDefaults().setDouble(currentVersion, forKey: sandboxVersionKey)
        
        //4. 返回比较结果
        return currentVersion > sandboxVersion
    }
    
    
    //统一设置导航栏和tabbar的一些属性
    private func setupAppearance(){
        
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
                
        UITabBar.appearance().tintColor = UIColor.orangeColor()
    }
    
    // 程序被销毁才会执行
    deinit {
        // 注销通知 - 只是一个习惯
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

